from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings

from .models import OAuthQQUser
from users.models import User
from oauth.utils import generate_access_token,check_access_token
import json,re
from django_redis import get_redis_connection
from django.contrib.auth import login

# Create your views here.

class QQFirstView(View):
    '''
    扫码登录页面链接获取函数
    # '''
    def get(self,request):
        # 1. 请求参数获取
        next = request.GET.get('next')
        # 2. 通过QQLoginTool获取登录链接
        oauth = OAuthQQ(
            # client_id: 在 QQ 互联申请到的客户端 id
            client_id=settings.QQ_CLIENT_ID,
            # client_secret: 我们申请的客户端秘钥
            client_secret=settings.QQ_CLIENT_SECRET,
            # redirect_uri: 我们申请时添加的: 登录成功后回调的路径
            redirect_uri=settings.QQ_REDIRECT_URI,
            # 用户完成整个qq登陆流程之后，返回到美多到哪个页面
            state=next,  # http://www.meiduo.site:8080/
        )
        # 调用对象的 get_qq_url() 函数, 获取对应的扫码页面:
        qq_login_url = oauth.get_qq_url()

        # 3. 构建响应返回
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'login_url':qq_login_url
        })

class QQUserView(View):
    '''
    QQ登录成功后，QQ会把用户重定向到美多
    '''
    def get(self,request):
        # 1. 获取请求参数code
        code = request.GET.get('code')

        oauth = OAuthQQ(

            client_id=settings.QQ_CLIENT_ID,

            client_secret=settings.QQ_CLIENT_SECRET,

            redirect_uri=settings.QQ_REDIRECT_URI,
            # 用户完成整个qq登陆流程之后，返回到美多到哪个页面
            state=next)  # http://www.meiduo.site:8080/
        # 2. 根据code提取AccessToken
        try:
            access_token = oauth.get_access_token(code)
            # 3. 根据Token获取openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'code有误！'
            })

        # 4. 根据openid判断用户是否已经注册美多用户
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist as e:
         # 用户没有绑定，返回加密后对openid —— 前端让用户数据用户名和密码，后续接口再去判断绑定
            token = generate_access_token(openid)
            return JsonResponse({
                'code':400,
                'errmsg':'未绑定',
                'access_token':token
            })

        # openid已经绑定美多用户
        else:
        # 根据user外键， 获取对应的 QQ 用户(user)----> user是一个外键
            user = qq_user.user
        # 设置状态保持
            login(request,user)
        # 设置cookie
            response = JsonResponse({
                'code':0,
                'errmsg':'ok'
            })
            response.set_cookie('username',user.username)
            return response

    def post(self,request):
        # 1. 获取请求参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')
        # 2. 验证用户信息
        if not all([mobile,password,sms_code,access_token]):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少参数！'
            })
            # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入正确的手机号码'})

            # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                             'errmsg': '请输入8-20位的密码'})
            #判断手机验证码是否过期
        conn = get_redis_connection('verify_code')
        sms_code_from_redis = conn.get('sms_%s' % mobile)
        if not sms_code_from_redis:
            return JsonResponse({'code': 400, 'errmsg': '手机验证码过期！'})
             # 判断手机验证码是否有误
        if sms_code != sms_code_from_redis.decode():
            return JsonResponse({'code': 400, 'errmsg': '验证码有误'})
            #判断Token是否有效
        openid = check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': 'token无效！'})
        # 3. 判断用户是否已经存在
        try:
            user = User.objects.get(mobile=mobile)
            # 3.1 用户不存在，新建绑定，把用户的openid和手机号存储再数据库中
        except User.DoesNotExist as e:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )
            try:
                OAuthQQUser.objects.create(
                    user=user,
                    openid=openid
                )
            except Exception as e:
                return JsonResponse({
                    'code':400,
                    'errmsg':'用户绑定失败！'
                })
            # 3.2 用户存在，直接绑定，并把信息存储再数据库中
        else:
            if not user.check_password(password):
                return JsonResponse({
                    'code':400,
                    'errmsg':'用户名或者密码错误!'
                })
            try:
                OAuthQQUser.objects.create(
                    user=user,
                    openid=openid
                )
            except Exception  as e:
                return JsonResponse({
                    'code':400,
                    'errmsg':'用户绑定失败！'
                })
        login(request,user)
        # 4. 构建响应返回
        response = JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
        response.set_cookie('username',user.username)
        return response

#
#
#
#





